const router = require('koa-router')();
const validRules = require('../lib/utils').validRules;

/**
 * save a card once;
 */
router.post('/', httpResult.resp(async ctx => {
  return 'ok';
}));
/**
 * post an array of msg card to save or update
 * save all in turns, but if some items fail in valid or save. throw failList out.
 *
 * return all ids in array when all succeed.
 */
router.post('/list', httpResult.resp(async ctx => {
  let admin = ctx.session.admin;
  let cards = ctx.request.body;


  ctx.assert(cards, 'request body is empty');
  ctx.assert(_.isArray(cards), 'request body not array');
  ctx.assert(cards.length <= 12, 'max cards length = 12');

  let failList = [];

  for(let item of cards){
    try{
      //TODO valid create save
      isValidCardItem(item);
      if(item._id){
        await models.messageCard.updateOne({_id : item._id}, {$set : item});
      }else{
        let instance = await models.messageCard.create(item);
        item._id = instance._id;
      }
    }catch(err){
      failList.push(err.message);
    }
  }
  if(failList.length > 0){
    throw JSON.stringify(failList);
  }else{
    return cards.map(it => it._id)
  }
}));

let cardRules = [{
  key : 'title',
  max : 200,
  message : 'title text over length, max length is 200'
},{
  key : 'description',
  max : 2000,
  message : 'description text over length, max length is 2000'
},{
  key : 'suggestions',
  max : 4,
  message : 'suggestions menu over length, length is 4'
}];

function isValidCardItem(item){
  if(item.title || item.description || item.media){
    validRules(item, cardRules);
  }else{
    throw new Error('title, description, media should at least have one');
  }
  return true;
}
module.exports = router;
